﻿#include "externaltools.h"
#include <QMessageBox>



//-----------------------------------------------------
Tesseract::Tesseract(QObject *parent) :
	QObject(parent)
{
}
//-----------------------------------------------------------
void Tesseract::runOCROn (const QStringList& sourceFileNames)
{
	m_anim = new Anim ();
	m_anim->show ();
	QApplication::processEvents ();

	m_resultFileList.clear ();

	m_processCount = sourceFileNames.size ();
	m_processError = false;
	static const QString args ("-l fra");
	static const QString commandTxt ("tesseract %1 %2 %3");

	foreach (const QString& file, sourceFileNames) {
		const QFileInfo fi (file);
		const QString resultFileName (Config::appWorkPath () + fi.baseName ());
		m_resultFileList << resultFileName + ".txt";

		const QString commandLine (commandTxt
							 .arg (file)
							 .arg (resultFileName)
							 .arg (args)
							 );

		qDebug () << tr ("Exécute : %1").arg (commandLine);

		m_process = new QProcess (this);

		connect (m_process,
				 SIGNAL(finished(int)),
				 this,
				 SLOT(onProcessFinished(int)));

		connect (m_anim,
				 SIGNAL(stopProcess ()),
				 this,
				 SLOT(cancelAnalysis()));

		m_cancelled = false;
		m_process->start (commandLine);
		m_process->waitForStarted ();
	}
}
//------------------------------------------
void Tesseract::onProcessFinished (const int code)
{
	if (code != 0) {
		m_processError = true;
		m_processCount = 0;
	}
	else {
		m_processCount--;
	}

	if (m_processCount == 0) {
		delete m_anim;

		if (!m_processError) {
			if (!m_cancelled)
				emit endOfOCR (m_resultFileList);
		}
		else {
			qDebug () << tr ("Une erreur est survenue, la ROC a échoué");
		}
	}

	QApplication::processEvents ();
}

void Tesseract::cancelAnalysis()
{
	m_cancelled = true;
	m_process->terminate ();
}
